package com.atguigu.gulimall.ware.listener;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.StockLockedDetailTo;
import com.atguigu.common.to.mq.StockLockedTo;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.atguigu.gulimall.ware.entity.WareOrderTaskEntity;
import com.atguigu.gulimall.ware.feign.OrderFeignService;
import com.atguigu.gulimall.ware.service.WareOrderTaskDetailService;
import com.atguigu.gulimall.ware.service.WareOrderTaskService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.OrderVo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@RabbitListener(queues = "stock.release.stock.queue")
public class StockReleaseListener {
    @Autowired
    WareSkuService wareSkuService;
    @Autowired
    OrderFeignService orderFeignService;
    @Autowired
    WareOrderTaskService orderTaskService;
    @Autowired
    WareOrderTaskDetailService orderTaskDetailService;

    /**
     * 库存自动解锁
     *
     * @param stockLockedTo
     * @param message
     * @param channel
     */
    @RabbitHandler
    public void handleStockAutoLockedRelease(StockLockedTo stockLockedTo,
                                             Message message,
                                             Channel channel) throws IOException {
        // 收到解锁库存的消息
        System.out.println("收到自动解锁库存的消息");
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            wareSkuService.unLockStock(stockLockedTo);
            // 手动确认消息消费成功
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            e.printStackTrace();
            // 拒绝消息
            channel.basicReject(deliveryTag, true);
        }

    }

    /**
     * 库存手动解锁
     *
     * @param orderTo
     * @param message
     * @param channel
     */
    @RabbitHandler
    public void handleOrderCloseRelease(OrderTo orderTo,
                                        Message message,
                                        Channel channel) throws IOException {
        // 收到解锁库存的消息
        System.out.println("收到订单关闭，准备解锁库存的消息");
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            wareSkuService.unLockStock(orderTo);
            // 手动确认消息消费成功
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            e.printStackTrace();
            // 拒绝消息
            channel.basicReject(deliveryTag, true);
        }

    }
}
